package hashmap;

import io.netty.channel.ChannelHandlerContext;

import java.util.HashMap;
import java.util.concurrent.Semaphore;

public class ChannelMng {
	private static Semaphore channelMapSem = new Semaphore(1);
	private static HashMap<String, ChannelObj> channelMap = new HashMap<String, ChannelObj>();
	
	private static void lockChannelMap() {
		try {
			channelMapSem.acquire();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
	private static void unlockChannelMap() {
		channelMapSem.release();
	}
	
	public static ChannelHandlerContext getChannel(String macstr) {
		ChannelObj co = null;
		lockChannelMap();
		co = channelMap.get(macstr);
		unlockChannelMap();
		if(co == null) return null;
		return co.cc;
	}

	public static ChannelObj getChannelObj(String macstr) {
		ChannelObj co = null;
		lockChannelMap();
		co = channelMap.get(macstr);
		unlockChannelMap();
		return co;
	}	
	
	public static void addChannel(String macstr, ChannelHandlerContext cc) {
		lockChannelMap();
		ChannelObj co = new ChannelObj();
		co.cc = cc;
		channelMap.put(macstr, co);
		unlockChannelMap();
		return;
	}	
	
	public static void swChannel(String macstr, ChannelHandlerContext cc) {
		lockChannelMap();
		ChannelObj co = new ChannelObj();
		co.cc = cc;		
		channelMap.put(macstr, co);
		unlockChannelMap();
		return;
	}	
	
	public static void removeChannel(String macstr){
		lockChannelMap();
		channelMap.remove(macstr);
		unlockChannelMap();
		return;
	}
}